/** @type {HTMLCanvasElement} */

import { randomColor, randomNum } from '../util/index.js'

const canvas = document.querySelector('#canvas')
const width = window.innerWidth
const height = window.innerHeight
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')

const tailStyle = {
    len: 10,
    startColor: '#d63031',
    endColor: '#fd79a8'
}

const circleNum = 12

//秩序编制者
const speed = {
    x: 10,
    y: 10
}

// const colors = ['#55efc4', '#0984e3', '#d63031', '#e67e22']

function Circle(x, y, r, vx, vy, color) {
    this.x = x
    this.y = y
    this.r = r
    this.vx = vx
    this.vy = vy
    this.color = color

    this.lastPoint = { x: 0, y: 0 }

    this.draw = function () {
        ctx.beginPath()
        ctx.lineWidth = 0
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false)
        ctx.fillStyle = this.color
        ctx.fill()
        this.drawTail()
    }

    this.drawTail = function () {
        ctx.beginPath()
        ctx.lineWidth = this.r * 2
        // ctx.lineCap = 'round'
        // ctx.lineJoin = 'round'
        ctx.moveTo(this.lastPoint.x, this.lastPoint.y)
        ctx.lineTo(this.x, this.y)
        ctx.strokeStyle = this.color

        // ctx.shadowColor = this.color
        // ctx.shadowBlur = 16

        ctx.stroke()
    }

    this.update = function () {
        this.lastPoint.x = this.x
        this.lastPoint.y = this.y

        this.x += this.vx
        this.y += this.vy

        //碰壁反弹
        if (this.x - this.r <= 0 || this.x + this.r >= width) {
            this.vx *= -1
        }
        if (this.y - this.r <= 0 || this.y + this.r >= height) {
            this.vy *= -1
        }
        this.draw()
    }
}


function randomPos() {
    const x = Math.floor(Math.random() * (width - 200) + 100)
    const y = Math.floor(Math.random() * (height - 200) + 100)
    return [x, y]
}

// function randomColor() {
//     const len = colors.length
//     return colors[Math.floor(Math.random() * len)]
// }

const circleArr = []

function init() {
    for (let i = 0; i < circleNum; i++) {
        // const vx = randomNum(3,12)
        // const vy = randomNum(3,12)
        const circle = new Circle(...randomPos(), 10, speed.x, speed.y, randomColor())
        circleArr.push(circle)
    }
}

init()

function animate() {
    window.requestAnimationFrame(animate)
    ctx.fillStyle = 'rgba(45, 52, 54, 0.05)'
    ctx.fillRect(0, 0, width, height)
    // ctx.clearRect(0,0,width,height)

    circleArr.forEach(c => {
        c.update()
    })
}

animate()